package com.vedana.bankmobile.shared.protobuf.serializers;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.vedana.bankmobile.shared.Operation;
import com.vedana.bankmobile.shared.protobuf.BankProto.OperationMsg;

/**
 * Serialize Operation domain objects to protobuf messages
 * 
 * @author Didier MOISE
 *
 */
public class OperationSerializer {
	private static final DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

	/**
	 * Read Operation POJO from protobuf message
	 * @param msg Protobuf message
	 * @return Operation POJO
	 */
	public static Operation readFromMsg(OperationMsg msg) {
		Operation operation = new Operation();

		operation.setAccountId(msg.getAccId());
		try {
			operation.setDate(df.parse(msg.getDate()));
		} catch (ParseException e) {
		}
		operation.setLabel(msg.getLabel());
		operation.setValue(msg.getValue());

		return operation;
	}

	/**
	 * Write Operation POJO to protobuf message
	 * @param operation Operation POJO
	 * @return Protobuf message
	 */
	public static OperationMsg writeToMsg(Operation operation) {
		OperationMsg msg = OperationMsg.newBuilder()
				.setAccId(operation.getAccountId())
				.setDate(df.format(operation.getDate()))
				.setLabel(operation.getLabel())
				.setValue(operation.getValue())
				.build();
		return msg;
	}

	/**
	 * Read List of operation POJO from protobuf message
	 * @param msg Protobuf message
	 * @return Operation POJO list
	 */
	public static List<Operation> readListFromMsg(List<OperationMsg> msg) {
		List<Operation> operations = new ArrayList<Operation>();
		for (OperationMsg m : msg) {
			operations.add(readFromMsg(m));
		}
		return operations;
	}

	/**
	 * Write Operation POJO list to protobuf message
	 * @param operations Operation POJO list
	 * @return Protobuf message
	 */
	public static List<OperationMsg> writeListToMsg(List<Operation> operations) {
		List<OperationMsg> msg = new ArrayList<OperationMsg>();
		for (Operation operation : operations) {
			msg.add(writeToMsg(operation));
		}
		return msg;
	}
}
